/**
 * 2017.11.9 ChenJiaWei
 */
import axios from "axios";
import querystring from "querystring";

const pro = process.env.NODE_ENV === "production";
const host = pro
  ? "https://565tech.com/admin"
  : "https://565tech.com/admin";
axios.defaults.baseURL = host;
axios.interceptors.request.use(
  config => {
    config.headers.common["Authorization"] = window.sessionStorage.TOKEN || "";
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

axios.interceptors.response.use(
  res => {
    return res;
  },
  err => {
    return Promise.reject(err);
  }
);
const get = (url, param, callback) => {
  url += "?" + querystring.stringify(param);
  axios
    .get(url)
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
const post = (url, param, callback) => {
  axios
    .post(url, querystring.stringify(param))
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
const put = (url, param, callback) => {
  axios
    .put(url, querystring.stringify(param))
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
const del = (url, param, callback) => {
  url += "?" + querystring.stringify(param);
  axios
    .delete(url)
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
const patch = (url, param, callback) => {
  axios
    .patch(url, querystring.stringify(param))
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
const head = (url, param, callback) => {
  url += "?" + querystring.stringify(param);
  axios
    .head(url)
    .then(res => {
      requestBack(res, callback);
    })
    .catch(err => {
      requestError(err, callback);
    });
};
function requestBack(res, callback) {
  console.debug("请求地址", res.request.responseURL);
  console.debug("请求结果", res.data);
  if (callback) {
    callback(res.data);
  }
}
function requestError(res, callback) {
  if (res.response) {
    let status = res.response.status;
    let error = res.response.data.error;
    switch (status) {
      case 400:
        console.error(error || "请求错误！");
        break;
      case 401:
        console.error("没有权限！");
        window.sessionStorage.clear();
        //跳转登录
        location.href = "#/login";
        break;
      case 403:
        console.error("服务器拒绝请求！");
        break;
      case 404:
        console.error("没有找到资源！");
        break;
      case 500:
        console.error("系统错误！");
        break;
      default:
        break;
    }
  }
}

export { get, post, del, head, put, patch, host, axios };
